layui.use(['transfer', 'util'], function () {
    const $ = layui.$
        , transfer = layui.transfer
        , util = layui.util;

    let teamStuCode = sessionStorage.getItem("teamStudentCode");

    //查询所有未分配小组的学生用户
    let result = commonAjax(AUTH_SERVER_URL+'/user/findUngroupedUser', "", 'get');

    //该小组已经分配的学生用户
    let selected = commonAjax(STU_APP_URL+'/userTeamRelation/findByTeamCode', {teamCode: teamStuCode}, 'get');
    let selectedValue = selectedData(selected.data);
    //字符串转化为Object
    let obj = eval('[' + selectedValue + ']');

    let title = ['所有成员', '现有成员'];

    transfer.render({
        elem: '#members'
        , data: result.data
        , id: 'key'
        , title: title
        , showSearch: true
        , value: obj
        , parseData: function (res) {
            return {
                "value": res.code,
                "title": res.username,
                "disabled": false,
                "checked": '',
            }
        }
    });

    //按钮事件
    util.event('lay-demoTransferActive', {
        //获取数据
        getData: function (othis) {
            let getData = transfer.getData('key');
            let codes = [];
            for (let i = 0; i < getData.length; i++) {
                codes += getData[i].value + ',';
            }
            if (codes.length !== 0) {
                codes = codes.substring(0, codes.lastIndexOf(','));
            }
            sendData(codes);
        }
        //重置
        , reload: function () {
            transfer.reload('key', {
                data: result.data
                , title: title
                , value: obj
                , showSearch: true
                , parseData: function (res) {
                    return {
                        "value": res.code,
                        "title": res.username,
                        "disabled": false,
                        "checked": '',
                    }
                }
            })
        }
    });

    /**
     * 发送数据
     * @param codes 用户编号集合
     */
    function sendData(codes) {
        let result = commonBatchAjax(STU_APP_URL+'/team/distributeMembers?teamCode=' + teamStuCode, {codes: codes}, 'post');
        if (result.code === 200) {
            layerMsgTreeOperatingSuccess();
        } else {
            layerMsgOperatingFail();
        }
    }

    /**
     * 获取已拥有组员userCodes集合
     * @param data
     */
    function selectedData(data) {
        let userCodes = [];
        if (data.length !== 0) {
            for (let i = 0; i < data.length; i++) {
                userCodes += "'" + data[i].userCode + "',"
            }
            if (userCodes.length !== 0) {
                userCodes = userCodes.substring(0, userCodes.lastIndexOf(','));
            }
        }
        return userCodes;
    }
});